#!/bin/bash
#################################################################
# @Description: 用例名称：日志处理与分析-目录修改监控回溯，测试目的：修改文件(新增/删除/内容变动)后，通过日志记录的文件修改的进程、修改时间进行回溯
# @Date : 2023-11-22
# @Last Modified by :
# @Last Modified time:2023-11-25
#################################################################

echo "测试前准备：安装监控工具软件包sysmonitor"
yum install -y sysmonitor > /dev/null
systemctl start sysmonitor
# 重启 rsyslog 服务后，日志会存储到 /var/log/sysmonitor.log
systemctl restart rsyslog
sleep 2

echo "开始测试："
echo "1.检查sysmonitor和rsyslog服务状态是否为运行"
#确认服务启动正常，状态为“active (running)”
systemctl status sysmonitor | grep "active (running)" > /dev/null
if [ $? -ne 0 ]; then
  echo "sysmonitor 服务异常，请检查！ "
  exit 1
fi
# 确认rsyslog服务的状态
systemctl status rsyslog | grep "active (running)" > /dev/null
if [ $? -ne 0 ]; then
  echo "rsyslog 服务异常，请检查！ "
  exit 1
fi

echo "2.添加目录监控，对home目录下增加和删除文件的情况进行监控" 
echo "/home 0x300"  >> /etc/sysmonitor/file 

echo "3.修改配置项重新加载并重启服务使其生效" 
systemctl reload sysmonitor
systemctl restart sysmonitor
sleep 5

# 随机生成创建的文件名
new_file_name=$(cat /dev/urandom | tr -dc 'a-zA-Z' | fold -w 8 | head -n 1).file 
echo "4.在home目录下新增文件 $new_file_name"
cd /home 
touch  $new_file_name
sleep 5

echo "5.查看/var/log/sysmonitor.log日志，有home目录下的文件的增加说明"
#echo -e "参考命令:\e[32m vi /var/log/sysmonitor.log\e[0m"
grep "Subfile" /var/log/sysmonitor.log | grep "was added" | grep "home" | grep $new_file_name |grep "parent" 
if [ $? -ne 0 ]; then
  echo -e "监控关键目录或文件修改\e[31m 测试未通过\e[0m"
else
  echo -e "监控关键目录或文件修改\e[32m 测试通过\e[0m"
fi

## 后处理
echo "测试完成进行环境清理"
sed -i '/\/home 0x300/d' /etc/sysmonitor/file 
yum remove -y sysmonitor > /dev/null
rm -f  $new_file_name
rm -rf /var/log/sysmonitor.log


